package com.ruoyi.wechat.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WechatCustomerConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wechat.AccessToken;
import com.ruoyi.common.utils.wechat.RequestUtils;
import com.ruoyi.system.tokenUnits.WxLoginUser;
import com.ruoyi.system.tokenUnits.WxTokenService;
import com.ruoyi.wechat.domain.WxUser;
import com.ruoyi.wechat.domain.WxUserOnlineLog;
import com.ruoyi.wechat.domain.dto.LoginUserDto;
import com.ruoyi.wechat.domain.vo.WxUserVo;
import com.ruoyi.wechat.mapper.WxUserMapper;
import com.ruoyi.wechat.mapper.WxUserOnlineLogMapper;
import com.ruoyi.wechat.service.IWxUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 微信用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-08-21
 */
@Service
public class WxUserServiceImpl implements IWxUserService 
{
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private WxUserOnlineLogMapper wxUserOnlineLogMapper;

    @Autowired
    private WxTokenService wxTokenService;

    @Autowired
    private WechatCustomerConfig wechatCustomerConfig;

//    @Value("${wechat.customer.appId}")
//    private String appid;

//    @Value("${wechat.customer.appSecret}")
//    private String secret;

    /**
     * 查询微信用户
     * 
     * @param id 微信用户主键
     * @return 微信用户
     */
    @Override
    public WxUser selectWxUserById(Long id)
    {
        return wxUserMapper.selectWxUserById(id);
    }

    /**
     * 查询微信用户列表
     * 
     * @param wxUser 微信用户
     * @return 微信用户
     */
    @Override
    public List<WxUser> selectWxUserList(WxUser wxUser)
    {
        return wxUserMapper.selectWxUserList(wxUser);
    }

    /**
     * 新增微信用户
     * 
     * @param wxUser 微信用户
     * @return 结果
     */
    @Override
    public int insertWxUser(WxUser wxUser)
    {
        return wxUserMapper.insertWxUser(wxUser);
    }

    /**
     * 修改微信用户
     * 
     * @param wxUser 微信用户
     * @return 结果
     */
    @Override
    public int updateWxUser(WxUser wxUser)
    {
        return wxUserMapper.updateWxUser(wxUser);
    }

    /**
     * 批量删除微信用户
     * 
     * @param ids 需要删除的微信用户主键
     * @return 结果
     */
    @Override
    public int deleteWxUserByIds(Long[] ids)
    {
        return wxUserMapper.deleteWxUserByIds(ids);
    }

    /**
     * 删除微信用户信息
     * 
     * @param id 微信用户主键
     * @return 结果
     */
    @Override
    public int deleteWxUserById(Long id)
    {
        return wxUserMapper.deleteWxUserById(id);
    }

    @Override
    public WxUserVo loginRegister(LoginUserDto loginDto) {

        //获取令牌
        String accessToken= AccessToken.getAccessToken(wechatCustomerConfig.getAppId(), wechatCustomerConfig.getAppSecret());
        // 通过code获取手机信息
        JSONObject phoneObj = RequestUtils.getPhoneByCode(accessToken, loginDto.getPhoneCode());
        String phone = phoneObj.getJSONObject("phone_info").getString("phoneNumber");

        // 通过code获取openid
        JSONObject openObj = RequestUtils.getOpenIdByCode(wechatCustomerConfig.getAppId(), wechatCustomerConfig.getAppSecret(), loginDto.getCode());
        String openId = openObj.getString("openid");
        WxUser wxUser= wxUserMapper.selectWxUserByOpenId(openId);
        if (wxUser==null){
            wxUser=new WxUser();
            wxUser.setOpenid(openId);
            wxUser.setUserTel(phone);
            wxUser.setUserName(loginDto.getNickName());
            wxUser.setWxProfileImg(loginDto.getAvat());
            wxUserMapper.insertWxUser(wxUser);
        } else {
            boolean isUpdate = false;
            if (!wxUser.getUserTel().equals(phone)) {
                isUpdate = true;
                wxUser.setUserTel(phone);
            }
            if (StringUtils.isNotEmpty(loginDto.getAvat()) && !wxUser.getWxProfileImg().equals(loginDto.getAvat())) {
                isUpdate = true;
                wxUser.setWxProfileImg(loginDto.getAvat());
            }
            if (StringUtils.isNotEmpty(loginDto.getNickName()) && !wxUser.getUserName().equals(loginDto.getNickName())) {
                isUpdate = true;
                wxUser.setUserName(loginDto.getNickName());
            }
            if (isUpdate) {
                wxUserMapper.updateWxUser(wxUser);
            }
        }
        String token= recordLoginInfo(wxUser);
        WxUserVo wxUserVo=(WxUserVo)wxUser;
        wxUserVo.setToken(token);
        return wxUserVo;
    }

    String recordLoginInfo(WxUser wxUser){
        // 获取登录令牌
        WxLoginUser wxLoginUser=new WxLoginUser();
        wxLoginUser.setUserId(wxUser.getId());
        wxLoginUser.setOpenId(wxUser.getOpenid());
        wxLoginUser.setNickName(wxUser.getUserName());
        String token=wxTokenService.createToken(wxLoginUser);
        // 添加登录记录
        WxUserOnlineLog wxUserOnlineLog=new WxUserOnlineLog();
        wxUserOnlineLog.setHeadimg(wxUser.getWxProfileImg());
        wxUserOnlineLog.setUserType(1);
        wxUserOnlineLog.setIpaddr(wxLoginUser.getIpaddr());
        wxUserOnlineLog.setBrowser(wxLoginUser.getBrowser());
        wxUserOnlineLog.setOs(wxLoginUser.getOs());
        wxUserOnlineLog.setLoginLocation(wxLoginUser.getLoginLocation());
        wxUserOnlineLog.setOpenid(wxUser.getOpenid());
        wxUserOnlineLog.setLoginTime(new Date());
        wxUserOnlineLogMapper.insertWxUserOnlineLog(wxUserOnlineLog);
        return token;
    }


}
